package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.Merchant;
import com.zhentao.service.MerchantService;
import com.zhentao.service.MiddleService;
import com.zhentao.pojo.Middle;
import com.zhentao.util.ResponseResult;
import com.zhentao.util.TextModerationPlusUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/march")
public class ApMerchantLoginController {

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MiddleService middleService;

    @PostMapping("login")  // 使用更明确的 POST 方法
    public String login(@RequestBody Merchant merchant) {
        // 1. 参数校验
        if (merchant == null || merchant.getUsername() == null || merchant.getPassword() == null) {
            return "用户名和密码不能为空";
        }
        // 2. 构建安全的查询条件（实际应使用加密密码）
        QueryWrapper<Merchant> qw = new QueryWrapper<>();
        qw.eq("username", merchant.getUsername());
        // 注意：生产环境应使用加密后的密码进行比对
        qw.eq("password", merchant.getPassword());

        // 3. 执行查询
        List<Merchant> list = merchantService.list(qw);

        // 4. 处理结果
        if (list != null && !list.isEmpty()) {
            return "登录成功";
        } else {
            return "用户名或密码错误";
        }
    }
    @PostMapping("register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Merchant merchant) {
        Map<String, Object> result = new HashMap<>();

        // 1. 参数校验
        if (merchant == null) {
            result.put("success", false);
            result.put("message", "注册信息不能为空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }

        // 2. 字段校验
        if (merchant.getUsername() == null || merchant.getUsername().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名不能为空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }

        if (merchant.getPassword() == null || merchant.getPassword().length() < 6) {
            result.put("success", false);
            result.put("message", "密码长度不能少于6位");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }

        if (merchant.getPhone() == null || !merchant.getPhone().matches("^1[3-9]\\d{9}$")) {
            result.put("success", false);
            result.put("message", "手机号格式不正确");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }



        // 3. 检查用户名是否已存在
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", merchant.getUsername());
        if (merchantService.count(queryWrapper) > 0) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }

        // 4. 密码加密（示例使用MD5，生产环境建议使用BCrypt）
//        merchant.setPassword(DigestUtils.md5DigestAsHex(merchant.getPassword().getBytes()));

        // 5. 保存用户
        try {

            Middle middle = new Middle();
            ResponseResult responseResult= TextModerationPlusUtil.checkContent(merchant.getUsername());
            if(responseResult.getCode()==600){
                merchantService.save(merchant);
                middleService.save(middle);
            }
            boolean success = merchantService.save(merchant);
            if (success) {
                result.put("success", true);
                result.put("message", "注册成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "注册失败，请稍后再试");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册异常：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}
